using System;
using System.Linq;
using System.Reflection;

namespace Se.Framework.Common.Config.Providers
{
    public class AssemblyTypeProvider : TypeProviderBase
    {
        private Assembly baseAssembly;

        public int Order { get; private set; }

        public bool CaseSensitive { get; private set; }

        public override Type GetTypeByClassName(string className)
        {
            return baseAssembly.GetTypes().SingleOrDefault(p => string.Equals(p.Name, className, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase));
        }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            if (config["assembly"] != null)
            {
                baseAssembly = Assembly.Load(config["assembly"]);
            }

            if (config["caseSensitive"] != null)
            {
                CaseSensitive = bool.Parse(config["caseSensitive"]);
            }
            
            if (config["order"] != null)
            {
                Order = int.Parse(config["order"]);
            }
            base.Initialize(name, config);
        }
    }
}